package com.renchunlin.looerpager.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.renchunlin.looerpager.R
import com.renchunlin.looerpager.utils.SizeUtils

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/6/17.
 * PS: Not easy to write code, please indicate.
 */
class SobLooperPager : LinearLayout {

    private lateinit var bindTitleListener: BindTitleListener
    private lateinit var viewPager: SobViewPager
    private lateinit var title: TextView
    private lateinit var layoutContent: LinearLayout
    private lateinit var mInnerAdapter: InnerAdapter

    //设置轮播图显示数量（1，3）
    private enum class ShowPagerCount(var value: Int) {
        SINGLE(1), MULTI(3)
    }

    //设置默认显示轮播图个数
    private val defaultPagerCount: Int = ShowPagerCount.SINGLE.value

    //设置是否默认显示标题
    private val isTitleShow = false

    //设置切换持续时间
    private val switchTime = -1

    private var mIsTitleShow: Boolean = false
    private var pagerShowCount: Int = 0
    private var mSwitchTime: Int = 0

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        LayoutInflater.from(context).inflate(R.layout.looper_pager_layout, this)
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.SobLooperPager)
        //从typeArray中读取属性值
        mIsTitleShow =
            typeArray.getBoolean(R.styleable.SobLooperPager_is_title_show, isTitleShow)
        pagerShowCount =
            typeArray.getInteger(R.styleable.SobLooperPager_show_pager_count, defaultPagerCount)
        mSwitchTime = typeArray.getInteger(R.styleable.SobLooperPager_switch_time, switchTime)
        typeArray.recycle()
        init()
        //设置页面切换监听
        initEvent()
    }

    private fun initEvent() {
        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                //切换回调
            }

            override fun onPageSelected(position: Int) {
                //切换停下来会回调
                //停下来以后，设置标题
                val realPosition = position % mInnerAdapter.getDataSize()
                title.text = bindTitleListener.getTitle(realPosition)
                //指示器的逻辑
                updateIndicator()
            }

            override fun onPageScrollStateChanged(state: Int) {
                //状态改变的回调
            }

        })
    }

    private fun init() {
        viewPager = this.findViewById(R.id.looper_pager_vp)
        viewPager.offscreenPageLimit = 3  //设置预加载3页，同时显示三个页面，左右两边显示一点上一页和下一页
        viewPager.pageMargin = SizeUtils.dip2px(context, 10f) //设置轮播图的间距
        title = this.findViewById(R.id.looper_title_tv)
        title.visibility = if (mIsTitleShow) View.VISIBLE else View.GONE
        layoutContent = this.findViewById(R.id.looper_point_container_lv)
        if (mSwitchTime != -1) {
            viewPager.setLooperTime(mSwitchTime.toLong())
        }
    }

    fun setData(innerAdapter: InnerAdapter, bindTitleListener: BindTitleListener) {
        viewPager.adapter = innerAdapter
        this.bindTitleListener = bindTitleListener
        //可以得到数据个数，根据数据个数，来动态创建圆点，indicator
        this.mInnerAdapter = innerAdapter
        //指示器的逻辑
        updateIndicator()
        viewPager.currentItem = Int.MAX_VALUE / 2 + 1
    }

    abstract class InnerAdapter : PagerAdapter() {
        private lateinit var onPagerItemClickListener: OnPagerItemClickListener

        override fun getCount(): Int {
            return Int.MAX_VALUE
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view == `object`
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val realPosition = position % getDataSize()
            val itemView = getSubView(container, realPosition)
            //设置Banner的点击事件
            itemView.setOnClickListener {
                onPagerItemClickListener.onItemClick(realPosition)
            }
            container.addView(itemView)
            return itemView
        }

        abstract fun getDataSize(): Int

        abstract fun getSubView(container: ViewGroup, position: Int): View

        fun setOnPagerItemClickListener(onPagerItemClickListener: OnPagerItemClickListener) {
            this.onPagerItemClickListener = onPagerItemClickListener
        }

        //暴露外部点击banner方法
        interface OnPagerItemClickListener {
            fun onItemClick(position: Int)
        }
    }

    //指示器的逻辑
    private fun updateIndicator() {
        val count = mInnerAdapter.getDataSize()
        //添加之前西先清空所有
        layoutContent.removeAllViews()
        for (i in 0 until count) {
            val view = View(context)

            //判断循环的总页数刚好等于当前页吗
            if (viewPager.currentItem % mInnerAdapter.getDataSize() == i) {
                //view.setBackgroundColor(Color.parseColor("#ff0000"))
                view.setBackgroundDrawable(resources.getDrawable(R.drawable.shape_circle_red))
            } else {
                //view.setBackgroundColor(Color.parseColor("#ffffff"))
                view.setBackgroundDrawable(resources.getDrawable(R.drawable.shape_circle))
            }

            //设置大小
            val layout = LayoutParams(
                SizeUtils.dip2px(context, 8f),
                SizeUtils.dip2px(context, 8f)
            )
            layout.setMargins(
                SizeUtils.dip2px(context, 10f),
                0,
                SizeUtils.dip2px(context, 10f),
                0
            )
            view.layoutParams = layout
            //添加到容器
            layoutContent.addView(view)
        }
    }

    //暴露外部获取标题Listener
    interface BindTitleListener {
        fun getTitle(position: Int): String
    }
}